package com.com.gmail.at.vssabinin.adminclient;

import java.util.List;

import DTO.PassengerDTO;
import DTO.ScheduleDTO;
import DTO.TicketDTO;

import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;


public class PassengersOnTrainReview extends javax.swing.JDialog {

   
	private static final long serialVersionUID = 1L;
	
    public PassengersOnTrainReview(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setResizable(false);
        initComponents();
    }

    public static PassengersOnTrainReview passOnTrainInstance = new PassengersOnTrainReview(Main.mainInstance, true);
    public ScheduleDTO scheduleDTO = new ScheduleDTO();
    private List<PassengerDTO> passengers = null;
   
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        passengersOnTrainList = new javax.swing.JList();
        goBackButton = new javax.swing.JButton();

        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        passengersOnTrainList.setModel(new AbstractListModel() {
        	/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			String[] values = new String[] {};
        	public int getSize() {
        		return values.length;
        	}
        	public Object getElementAt(int index) {
        		return values[index];
        	}
        });
        jScrollPane1.setViewportView(passengersOnTrainList);

        goBackButton.setText("Go back");
        
        goBackButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
            	goBackMouseReleased(evt);
            }
        });
        
        
        JButton deleteButton = new JButton("Delete passenger");
        
        deleteButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
            	deleteButtonMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
        				.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(goBackButton)
        					.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        					.addComponent(deleteButton)))
        			.addContainerGap(0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 298, GroupLayout.PREFERRED_SIZE)
        			.addPreferredGap(ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(goBackButton)
        				.addComponent(deleteButton))
        			.addContainerGap())
        );
        getContentPane().setLayout(layout);

        pack();
    }
    
    private  DefaultListModel listModel = new DefaultListModel();

    @SuppressWarnings("unchecked")
	public void update() {
    	listModel.clear();
    	Main.mainInstance.client.sendThroughProtocol("adminViewPassengersOnTrain", scheduleDTO);
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	this.passengers = (List<PassengerDTO>) message.getObject();
            for (int i = 0; i < passengers.size(); i++) {
            	this.listModel.addElement("ID " + passengers.get(i).getPassengerID() + " Passenger:  " 
            + passengers.get(i).getPassengerName() + " " + passengers.get(i).getPassengerSurname() + "   " +
            		"date of birth:  " + passengers.get(i).getPassengerDateOfBirth().toString());
            }
        } else if (message.getType().equals("no")) {
        	listModel.addElement("No passengers on selected schedule");
        }
        PassengersOnTrainReview.passOnTrainInstance.passengersOnTrainList.setModel(listModel);
    }
    
    private void goBackMouseReleased(java.awt.event.MouseEvent evt) {
    	ScheduleManager.scheduleInstance.update();
        this.dispose();
        ScheduleManager.scheduleInstance.setVisible(true);
    }
    
    private void deleteButtonMouseReleased(java.awt.event.MouseEvent evt) {
    	int id = this.passengersOnTrainList.getSelectedIndex();
    	if (id != -1) {
    		int selection = JOptionPane.showConfirmDialog(null, "Are you shure, that you want to delete " +
    				"this passenger from the train (delete his ticket)!", "Warning", JOptionPane.YES_NO_OPTION, 
    				JOptionPane.WARNING_MESSAGE);
        	if (selection == JOptionPane.YES_OPTION) {
        		Integer trainNumber = scheduleDTO.getTrainNumber();
        		TicketDTO ticketToBeDeleted = null;
        		for (TicketDTO ticket: this.passengers.get(id).getTickets()) {
        			if (ticket.getSchedule().getTrainNumber().equals(trainNumber)) {
        				ticketToBeDeleted = ticket;
        			}
        		}
        		if (ticketToBeDeleted == null) {
        			JOptionPane.showMessageDialog(null, "Internal error!");
        			return;
        		}
        		Main.mainInstance.client.sendThroughProtocol("adminDeletePassengerFromTrain", ticketToBeDeleted);
                Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
                if (message.getType().equals("ok")) {
                	passOnTrainInstance.update();
                	JOptionPane.showMessageDialog(null, "You have successfully removed the passengers from the train!"); 
                } else {
                	JOptionPane.showMessageDialog(null, "Error during the removal of passenger!"); 
                	passOnTrainInstance.update();
                }
        	}
    	} else {
    		JOptionPane.showMessageDialog(null, "Illegal selection!"); 
    	}
    }
    
    
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PassengersOnTrainReview.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PassengersOnTrainReview.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PassengersOnTrainReview.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PassengersOnTrainReview.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PassengersOnTrainReview dialog = new PassengersOnTrainReview(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private javax.swing.JButton goBackButton;
    private javax.swing.JList passengersOnTrainList;
    private javax.swing.JScrollPane jScrollPane1;
}
